package com.helmlabs.grouper.accounts.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.helmlabs.grouper.accounts.model.Address;
import com.helmlabs.grouper.accounts.model.Role;
import com.helmlabs.grouper.accounts.model.UserProfile;

public class UserProfileDaoJdbc extends JdbcDaoSupport implements UserProfileDao {
	
	private RoleDao roleDao;

	public UserProfile get(Long id) {
		UserProfile profile = (UserProfile)this.getJdbcTemplate().queryForObject("SELECT * FROM users u, users_profile up WHERE u.uid = up.users_fk AND u.uid=? LIMIT 1", new Object[]{id}, new UserRowMapper());
		return profile;
	}

	public List<UserProfile> getAll(int page, int pageSize, String sort,
			String order) {
		return null;
	}

	public UserProfile getByUsername(String username) {
		Long id = this.getJdbcTemplate().queryForLong("SELECT uid FROM users u, users_profile up WHERE up.users_fk = u.uid AND up.email_address=? LIMIT 1", new Object[]{username});
		return get(id);
	}

	public UserProfile save(UserProfile userProfile) {
		return null;
	}
	
	private class UserRowMapper implements ParameterizedRowMapper {

		public Object mapRow(ResultSet rs, int index) throws SQLException {
			UserProfile userProfile = new UserProfile();
			userProfile.setId(rs.getLong("uid"));
			userProfile.setFirstName(rs.getString("first_name"));
			userProfile.setLastName(rs.getString("last_name"));
			userProfile.setEmail(rs.getString("email_address"));
			userProfile.setPhone(rs.getString("profile_phone"));
			
			Address address = new Address();
			address.setStreet1(rs.getString("profile_street1"));
			address.setStreet2(rs.getString("profile_street2"));
			address.setCity(rs.getString("profile_city"));
			address.setState(rs.getString("profile_state"));
			address.setZipCode(rs.getString("profile_zip"));
			address.setCountry(rs.getString("profile_country"));
			userProfile.setPrimaryAddress(address);
			userProfile.setPassword(rs.getString("password_encrypted"));
			userProfile.setRoles(roleDao.getActiveRolesForObject(Role.USER_ROLES, userProfile.getId()));
			userProfile.setAccountNonExpired(true);
			userProfile.setAccountNonLocked(true);
			userProfile.setCredentialsNonExpired(true);
			userProfile.setEnabled(true);
			return userProfile;
		}
		
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public List<UserProfile> getAllEmployeesByCompanyId(Long companyid) {
		String sql = "SELECT u.*, up.* FROM users u, users_profile up, users_company uc WHERE u.uid = up.users_fk AND uc.user_fk = u.uid AND uc.company_fk = ?";
		Object[] args = {companyid};
		return this.getJdbcTemplate().query(sql, args, new UserRowMapper());
	}

}
